import 'package:flutter/services.dart';

class MobilePhoneInputFormatter extends TextInputFormatter {
  Pattern regex2 = RegExp(r'(\d{4}\d{4})');

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    String newText = newValue.text.replaceAll(' ', '');
    if (newText.length > 11) return oldValue;
    bool reduceText = oldValue.text.length > newValue.text.length;
    bool endWithBlank = oldValue.text.endsWith(' ');

    String replaceText;
    if (newText.length >= 6) {
      replaceText = newText.replaceAllMapped(regex2, (match) {
        if (endWithBlank && reduceText) {
          return '${match[1]} ${match[2]}';
        }
        return '${match[1]} ${match[2]} ';
      });
    } else {
      replaceText = newText;
    }
    return TextEditingValue(
      text: replaceText,
      selection: TextSelection.collapsed(offset: replaceText.length),
    );
  }
}
